package com.cloudkinto.appletservice.order.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.appletservice.order.AppletOrderAmazonService;
import com.cloudkinto.appletservice.order.vo.amazon.AppletAmazonOrderDetailRes;
import com.cloudkinto.appletservice.order.vo.amazon.AppletAmazonOrderPageRes;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.error.ErrorEnum;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.exception.BizExceptionI18;
import com.cloudkinto.common.exception.NotSufficientFundsException;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.*;
import com.cloudkinto.service.finance.CompanyAccountService;
import com.cloudkinto.service.operate.OperateRecordService;
import com.cloudkinto.service.order.vo.amazon.AmazonOrderProductRes;
import com.cloudkinto.service.order.vo.amazon.UpdateSysMemoReq;
import com.cloudkinto.service.orderoutput.OrderOutputService;
import com.cloudkinto.service.orderoutput.vo.OrderOutputAddReq;
import com.cloudkinto.service.orderoutput.vo.OrderOutputPackageAddReq;
import com.cloudkinto.service.orderoutput.vo.OrderOutputProductAddReq;
import com.cloudkinto.service.region.JpRegionService;
import com.cloudkinto.service.shipprice.ShipPriceService;
import com.cloudkinto.service.shop.ShopService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author 张永远
 * @since 2020-06-02
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
@Slf4j
public class AppletOrderAmazonServiceImpl extends ServiceImpl<OrderAmazonDao, OrderAmazonDo> implements AppletOrderAmazonService {

    @Autowired
    private OrderAmazonDao dao;
    @Autowired
    private OrderAmazonItemsDao orderAmazonItemsDao;
    @Autowired
    private ShopDao shopDao;
    @Autowired
    private OrderOutputDao orderOutputDao;
    @Autowired
    private OrderOutputPackageDao orderOutputPackageDao;
    @Autowired
    private ProductSkuMapDao productSkuMapDao;
    @Autowired
    private ProductInfoDao productInfoDao;
    @Autowired
    private ShopService shopService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CompanyAccountService companyAccountService;
    @Autowired
    private ShipPriceService shipPriceService;
    @Autowired
    private JpRegionService mRegionService;
    @Autowired
    private StockRecordDao stockDao;
    @Autowired
    private StorageDao storageDao;
    @Autowired
    private OrderOutputService outputService;
    @Autowired
    private OperateRecordService operateRecordService;

    @Override
    public SingleResult addInit(Long userId, Long companyId) {
        List<Map> shopList = new ArrayList<>();
        UserDo userDo = userDao.selectById(userId);
        if (userDo == null) throw new BizExceptionI18("no.user.info");
        QueryWrapper shopWrapper = new QueryWrapper();
        if (userDo.getShopId() != null)
            shopWrapper.eq("id", userDo.getShopId());
        shopWrapper.eq("company_id", companyId);
        shopWrapper.eq("platform_id", 1);
        List<ShopDo> shopDoList = shopDao.selectList(shopWrapper);
        if (!CollectionUtils.isEmpty(shopDoList)) {
            for (ShopDo shopDo : shopDoList) {
                Map shopMap = new HashMap();
                shopMap.put("id", shopDo.getId());
                shopMap.put("value", shopDo.getShopName());
                shopList.add(shopMap);
            }
        }
        return SingleResult.success(shopList);
    }


    @Override
    public SingleResult markSendOut(List<Long> ids, Long userId) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new BizExceptionI18("pls.choose.order");
        }
        for (Long id : ids) {
            OrderAmazonDo orderAmazonDo = this.baseMapper.selectById(id);
            if (orderAmazonDo == null) throw new BizExceptionI18("no.order.info");
            if (orderAmazonDo.getIsSendOut() == 0) {
                orderAmazonDo.setIsSendOut(1);
                this.baseMapper.updateById(orderAmazonDo);
                operateRecordService.operateAddRecord(SysConstant.OPERATE_MARK_SEND, orderAmazonDo.getId(), userId, 4);
            }
        }
        return SingleResult.success();
    }

    @Override
    public SingleResult sendOut(String orderid, Long userId, Long companyId, boolean isAuto) {
        String[] ids = new String[]{orderid};
        sufficientFundsCheck(companyId);
        List<OrderOutputAddReq> orderOutputAddReqList = new ArrayList<>();
        List<String> failOrders = new ArrayList<>();
        for (String id : ids) {
            OrderAmazonDo orderAmazonDo = this.baseMapper.selectById(id);
            if (orderAmazonDo == null) throw new BizExceptionI18("no.order.info");
            LambdaQueryWrapper<OrderAmazonItemsDo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OrderAmazonItemsDo::getOrderAmazonId, id);
            List<OrderAmazonItemsDo> itemsDoList = orderAmazonItemsDao.selectList(wrapper);
            //订单
            OrderOutputAddReq res = new OrderOutputAddReq();
            res.setOrderType(1);
//        res.setStatus(0);
            res.setSendDate(new Date());
            res.setShopId(orderAmazonDo.getShopId());
            res.setCompanyId(orderAmazonDo.getCompanyId());
            res.setOrderNo(orderAmazonDo.getAmazonOrderNumber());
            res.setReceiverName(orderAmazonDo.getShipName());
            res.setTelPhone(orderAmazonDo.getShipPhone());
            res.setPostCode(orderAmazonDo.getPostalCode());
            res.setArea(orderAmazonDo.getShipStateOrRegion());
            if (StringUtils.isNotBlank(orderAmazonDo.getShipCity())) {
                res.setAddress(orderAmazonDo.getShipCity() + orderAmazonDo.getShipAddress());
            } else {
                res.setAddress(orderAmazonDo.getShipAddress());
            }
            if (orderAmazonDo.getLastDeliveryDate() != null && orderAmazonDo.getEarliestDeliveryDate() != null &&
                    "Scheduled".equals(orderAmazonDo.getShipmentServiceLevelCategory())) {
                res.setDeliveryDate(TimeUtils.formatDate(orderAmazonDo.getLastDeliveryDate()));
                int time1 = Integer.parseInt(TimeUtils.formatDate(orderAmazonDo.getEarliestDeliveryDate(), "HH")) + 1;
                String startTime = time1 < 10 ? "0" + time1 : String.valueOf(time1);
                int time2 = Integer.parseInt(TimeUtils.formatDate(orderAmazonDo.getLastDeliveryDate(), "HH")) + 1;
                String endTime = time2 < 10 ? "0" + time2 : String.valueOf(time2);
                res.setDeliveryTime(startTime +
                        "-" + endTime);
            }
            long storageId = 0L;
            //item
            List<OrderOutputProductAddReq> orderOutputProductDetailList = new ArrayList<>();
            List<OrderAmazonItemsDo> failedItems = new ArrayList<>();
            if (!CollectionUtils.isEmpty(itemsDoList)) {
                double[] size = new double[4];
                double shipPirce = 99999D;
                //默认仓库先捆包
                for (OrderAmazonItemsDo itemsDo : itemsDoList) {
                    Long productId = getProductId(itemsDo.getSellerSku(), orderAmazonDo.getCompanyId());
                    if (productId == null) {
                        failOrders.add(String.format("%s(未找到%s信息)", orderAmazonDo.getAmazonOrderNumber(), itemsDo.getSellerSku()));
                        continue;
                    }
                    Long stateId = mRegionService.getStateIdByPostCode(orderAmazonDo.getPostalCode());
                    if (stateId <= 8) {//大阪地区优先发货仓库
                        storageId = 9L;
                    } else {//东京仓库优先发货仓库
                        storageId = 10L;
                    }
                    LambdaQueryWrapper<StockRecordDo> wrapper1 = new LambdaQueryWrapper();
                    wrapper1.eq(StockRecordDo::getShopId, res.getShopId())
                            .eq(StockRecordDo::getProductInfoId, productId)
                            .eq(StockRecordDo::getStorageId, storageId);
                    StockRecordDo stockRecordDo = stockDao.selectOne(wrapper1);
                    int noDeliveredCount = stockDao.getOrderOutCount(productId, res.getShopId(), storageId);
                    int count = itemsDo.getQuantityOrdered() - itemsDo.getQuantityShipped();
                    if (count < 1) count = itemsDo.getQuantityOrdered();
                    if (stockRecordDo == null || stockRecordDo.getCanSellCount() - noDeliveredCount < count) {//优先仓库有库存，优先仓库发货
                        failedItems.add(itemsDo);
                        continue;
                    }
                    OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                    productDetail.setOrderId(itemsDo.getOrderAmazonId());
                    productDetail.setProductId(productId);
                    productDetail.setCount(count);
                    orderOutputProductDetailList.add(productDetail);
                }
                OrderOutputPackageAddReq packageDetail = new OrderOutputPackageAddReq();
                List<OrderOutputPackageAddReq> packageAddReqList = new ArrayList<>();
                packageDetail.setProductList(orderOutputProductDetailList);
                OrderOutputAddReq addReq = new OrderOutputAddReq();
                BeanUtils.copyProperties(res, addReq);
                packageAddReqList.add(packageDetail);
                addReq.setStorageId(storageId);
                addReq.setPackageList(packageAddReqList);
                //默认仓库库存不足
                if (orderOutputProductDetailList.size() > 0) {
                    orderOutputAddReqList.add(addReq);
                } else {
                    List<OrderOutputProductAddReq> productAddList = new ArrayList<>();
                    //剩余一件商品无库存
                    if (failedItems.size() == 1 && failedItems.get(0).getQuantityOrdered() - failedItems.get(0).getQuantityShipped() == 1) {
                        storageId = 0L;
                        Long productId = getProductId(failedItems.get(0).getSellerSku(), res.getCompanyId());
                        List<StorageDo> storageDos = storageDao.selectList(null);
                        int count = failedItems.get(0).getQuantityOrdered() - failedItems.get(0).getQuantityShipped();
                        if (count < 1) count = failedItems.get(0).getQuantityOrdered();
                        for (StorageDo storageDo : storageDos) {//遍历仓库是否都有库存
                            LambdaQueryWrapper<StockRecordDo> wrapper2 = new LambdaQueryWrapper();
                            wrapper2.eq(StockRecordDo::getShopId, res.getShopId())
                                    .eq(StockRecordDo::getProductInfoId, productId)
                                    .eq(StockRecordDo::getStorageId, storageDo.getId());
                            StockRecordDo stockRecordDo1 = stockDao.selectOne(wrapper2);
                            size = shipPriceService.countSameSkuSize(new double[4], productId, count);
                            int noDeliveredCount1 = stockDao.getOrderOutCount(productId, res.getShopId(), storageDo.getId());
                            if (stockRecordDo1 != null && stockRecordDo1.getCanSellCount() - noDeliveredCount1 >= count) {
                                List<ShipPriceDo> shipPriceDos = shipPriceService.queryByRegionAndSize(res.getPostCode(),
                                       size, res.getCod(), res.getShipmentType(), storageDo.getId(), 1, res.getCompanyId());
                                if (shipPriceDos.size() < 1 || shipPriceDos.get(0).getPrice() == 0) continue;
                                if (shipPirce > shipPriceDos.get(0).getPrice()) {//选择最便宜的价格
                                    shipPirce = shipPriceDos.get(0).getPrice();
                                    storageId = storageDo.getId();
                                }
                            }
                        }
                        OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                        productDetail.setProductId(productId);
                        productDetail.setCount(count);
                        productAddList.add(productDetail);
                        OrderOutputPackageAddReq packageDetail1 = new OrderOutputPackageAddReq();
                        if (storageId != 0) {
                            List<OrderOutputPackageAddReq> packageAddReqList1 = new ArrayList<>();
                            packageDetail1.setProductList(productAddList);
                            OrderOutputAddReq addReq1 = new OrderOutputAddReq();
                            BeanUtils.copyProperties(res, addReq1);
                            packageAddReqList1.add(packageDetail1);
                            addReq1.setStorageId(storageId);
                            addReq1.setPackageList(packageAddReqList1);
                            orderOutputAddReqList.add(addReq1);
                        } else {
                            failOrders.add(String.format("%s(%s库存不足)", orderAmazonDo.getAmazonOrderNumber(), failedItems.get(0).getSellerSku()));
                        }
                    } else {
                        //多件商品无库存，第二优先捆包
                        List<OrderAmazonItemsDo> productDoListFailed = new ArrayList<>();
                        LambdaQueryWrapper<StorageDo> lambdaQueryWrapper = new LambdaQueryWrapper();
                        lambdaQueryWrapper.eq(StorageDo::getSupportShip, 1)
                                .ne(StorageDo::getId, storageId);
                        List<StorageDo> storageDos = storageDao.selectList(lambdaQueryWrapper);
                        storageId = 0L;
                        if (storageDos != null) {
                            StorageDo storageDo = storageDos.get(0);//遍历支持捆包仓库是否都有库存
                            for (OrderAmazonItemsDo productDo :
                                    failedItems) {
                                Long productId = getProductId(productDo.getSellerSku(), res.getCompanyId());
                                int count = productDo.getQuantityOrdered() - productDo.getQuantityShipped();
                                if (count < 1) count = productDo.getQuantityOrdered();
                                LambdaQueryWrapper<StockRecordDo> wrapper1 = new LambdaQueryWrapper();
                                wrapper1.eq(StockRecordDo::getShopId, res.getShopId())
                                        .eq(StockRecordDo::getProductInfoId, productId)
                                        .eq(StockRecordDo::getStorageId, storageDo.getId());
                                StockRecordDo stockRecordDo = stockDao.selectOne(wrapper1);
                                int noDeliveredCount = stockDao.getOrderOutCount(productId, res.getShopId(), storageDo.getId());

                                if (stockRecordDo == null || stockRecordDo.getCanSellCount() - noDeliveredCount < count) {
                                    productDoListFailed.add(productDo);
                                    continue;
                                }
                                storageId = storageDo.getId();
                                OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                                productDetail.setProductId(productId);
                                productDetail.setCount(count);
                                productAddList.add(productDetail);

                            }
                            packageDetail = new OrderOutputPackageAddReq();
                            List<OrderOutputPackageAddReq> packageAddReqList1 = new ArrayList<>();
                            packageDetail.setProductList(productAddList);
                            OrderOutputAddReq addReq1 = new OrderOutputAddReq();
                            BeanUtils.copyProperties(res, addReq1);
                            packageAddReqList1.add(packageDetail);
                            if (storageId != 0) {
                                addReq1.setStorageId(storageId);
                                addReq1.setPackageList(packageAddReqList1);
                                orderOutputAddReqList.add(addReq1);
                            }
                        } else {
                            productDoListFailed.addAll(failedItems);
                        }
                        //所有捆包仓库无库存的产品
                        if (productDoListFailed.size() > 0) {//捆包仓库无库存，分别发
                            LambdaQueryWrapper<StorageDo> queryWrapper = new LambdaQueryWrapper();
                            queryWrapper.eq(StorageDo::getSupportShip, 0);
                            List<StorageDo> storageDoList = storageDao.selectList(queryWrapper);
                            for (OrderAmazonItemsDo productDo :
                                    productDoListFailed) {
                                storageId = 0L;
                                shipPirce = 99999D;
                                Long productId = getProductId(productDo.getSellerSku(), res.getCompanyId());
                                int count = productDo.getQuantityOrdered() - productDo.getQuantityShipped();
                                if (count < 1) count = productDo.getQuantityOrdered();
                                for (StorageDo storageDo : storageDoList) {//遍历仓库是否都有库存
                                    LambdaQueryWrapper<StockRecordDo> wrapper2 = new LambdaQueryWrapper();
                                    size = shipPriceService.countSameSkuSize(new double[4], productId,
                                            1);
                                    wrapper2.eq(StockRecordDo::getShopId, res.getShopId())
                                            .eq(StockRecordDo::getProductInfoId, productId)
                                            .eq(StockRecordDo::getStorageId, storageDo.getId());
                                    StockRecordDo stockRecordDo1 = stockDao.selectOne(wrapper2);
                                    int noDeliveredCount1 = stockDao.getOrderOutCount(productId, res.getShopId(), storageDo.getId());
                                    if (stockRecordDo1 != null && stockRecordDo1.getCanSellCount() - noDeliveredCount1 >= count) {
                                        List<ShipPriceDo> shipPriceDos = shipPriceService.queryByRegionAndSize(res.getPostCode(),
                                                size, res.getCod(), res.getShipmentType(), storageDo.getId(), 1, res.getCompanyId());
                                        if (shipPriceDos.size() < 1 || shipPriceDos.get(0).getPrice() == 0) continue;
                                        if (shipPirce > shipPriceDos.get(0).getPrice()) {//选择最便宜的价格
                                            shipPirce = shipPriceDos.get(0).getPrice();
                                            storageId = storageDo.getId();
                                        }
                                    }
                                }
                                if (storageId != 0) {
                                    OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                                    productDetail.setProductId(productId);
                                    productDetail.setCount(count);
                                    productAddList.add(productDetail);
                                } else {
                                    //剩余SKU都没有库存
                                    failOrders.add(String.format("%s(%s库存不足)", orderAmazonDo.getAmazonOrderNumber(), failedItems.get(0).getSellerSku()));
                                }
                            }
                            packageDetail = new OrderOutputPackageAddReq();
                            packageAddReqList = new ArrayList<>();
                            packageDetail.setProductList(productAddList);
                            addReq = new OrderOutputAddReq();
                            BeanUtils.copyProperties(res, addReq);
                            packageAddReqList.add(packageDetail);
                            if (storageId != 0) {
                                addReq.setStorageId(storageId);
                                addReq.setPackageList(packageAddReqList);
                                orderOutputAddReqList.add(addReq);
                            }
                        }
                    }
                }
            }
            if (orderOutputAddReqList.size() > 0) {
                operateRecordService.operateAddRecord(SysConstant.OPERATE_CLICK_SEND, orderAmazonDo.getId(), userId,4);
            }
        }
        for (OrderOutputAddReq outputAddReq : orderOutputAddReqList) {
            StringBuilder sku = new StringBuilder();
            int cout = 0;
            for (OrderOutputProductAddReq orderOutputProductAddReq : outputAddReq.getPackageList().get(0).getProductList()) {
                cout = cout + orderOutputProductAddReq.getCount();
                if (StringUtils.isNotBlank(sku)) {
                    sku.append(",");
                }
                sku.append(productInfoDao.selectById(orderOutputProductAddReq.getProductId()).getCommoditySku());
            }
            outputAddReq.setSku(sku.toString());
            outputAddReq.setCount(cout);
        }
        if (isAuto) {
            sendOutMatch(orderOutputAddReqList, userId);
        }
        Map map = new HashMap();
        map.put("orderList", orderOutputAddReqList);
        map.put("failedList", failOrders);
        map.put("storageList", storageDao.selectList(null));
        return SingleResult.success(map);
    }

    @Override
    public SingleResult sendOutNopackage(String id, Long userId, Long companyId) {
        sufficientFundsCheck(companyId);
        List<OrderOutputAddReq> orderOutputAddReqList = new ArrayList<>();
        List<String> failOrders = new ArrayList<>();
        OrderAmazonDo orderAmazonDo = this.baseMapper.selectById(id);
        if (orderAmazonDo == null) throw new BizExceptionI18("no.order.info");
        LambdaQueryWrapper<OrderAmazonItemsDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderAmazonItemsDo::getOrderAmazonId, id);
        List<OrderAmazonItemsDo> itemsDoList = orderAmazonItemsDao.selectList(wrapper);
        //订单
        OrderOutputAddReq res = new OrderOutputAddReq();
        res.setOrderType(1);
//        res.setStatus(0);
        res.setSendDate(new Date());
        res.setShopId(orderAmazonDo.getShopId());
        res.setCompanyId(orderAmazonDo.getCompanyId());
        res.setOrderNo(orderAmazonDo.getAmazonOrderNumber());
        res.setReceiverName(orderAmazonDo.getShipName());
        res.setTelPhone(orderAmazonDo.getShipPhone());
        res.setPostCode(orderAmazonDo.getPostalCode());
        res.setArea(orderAmazonDo.getShipStateOrRegion());
        if (StringUtils.isNotBlank(orderAmazonDo.getShipCity())) {
            res.setAddress(orderAmazonDo.getShipCity() + orderAmazonDo.getShipAddress());
        } else {
            res.setAddress(orderAmazonDo.getShipAddress());
        }
        if (orderAmazonDo.getLastDeliveryDate() != null && orderAmazonDo.getEarliestDeliveryDate() != null &&
                "Scheduled".equals(orderAmazonDo.getShipmentServiceLevelCategory())) {
            try {
                res.setDeliveryDate(TimeUtils.formatDate(orderAmazonDo.getLastDeliveryDate()));
                int time1 = Integer.parseInt(TimeUtils.formatDate(orderAmazonDo.getEarliestDeliveryDate(), "HH")) + 1;
                String startTime = time1 < 10 ? "0" + time1 : String.valueOf(time1);
                int time2 = Integer.parseInt(TimeUtils.formatDate(orderAmazonDo.getLastDeliveryDate(), "HH")) + 1;
                String endTime = time2 < 10 ? "0" + time2 : String.valueOf(time2);
                res.setDeliveryTime(startTime +
                        "-" + endTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //item
        List<OrderOutputProductAddReq> orderOutputProductDetailList = new ArrayList<>();
        LambdaQueryWrapper<StorageDo> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(StorageDo::getSupportShip, 0);
        List<StorageDo> storageDoList = storageDao.selectList(queryWrapper);
        for (OrderAmazonItemsDo productDo :
                itemsDoList) {
            long storageId = 0L;
            double shipPirce = 99999D;
            int count = productDo.getQuantityOrdered() - productDo.getQuantityShipped();
            if (count < 1) count = productDo.getQuantityOrdered();
            Long productId = getProductId(productDo.getSellerSku(), res.getCompanyId());
            for (StorageDo storageDo : storageDoList) {//遍历仓库是否都有库存
                LambdaQueryWrapper<StockRecordDo> wrapper2 = new LambdaQueryWrapper();
                double[] size = shipPriceService.countSameSkuSize(new double[4], productId,
                        1);
                wrapper2.eq(StockRecordDo::getShopId, res.getShopId())
                        .eq(StockRecordDo::getProductInfoId, productId)
                        .eq(StockRecordDo::getStorageId, storageDo.getId());
                StockRecordDo stockRecordDo1 = stockDao.selectOne(wrapper2);
                int noDeliveredCount1 = stockDao.getOrderOutCount(productId, res.getShopId(), storageDo.getId());
                if (stockRecordDo1 != null && stockRecordDo1.getCanSellCount() - noDeliveredCount1 >= count) {
                    List<ShipPriceDo> shipPriceDos = shipPriceService.queryByRegionAndSize(res.getPostCode(),
                           size, res.getCod(), res.getShipmentType(), storageDo.getId(), 1, res.getCompanyId());
                    if (shipPriceDos.size() < 1 || shipPriceDos.get(0).getPrice() == 0) continue;
                    if (shipPirce > shipPriceDos.get(0).getPrice()) {//选择最便宜的价格
                        shipPirce = shipPriceDos.get(0).getPrice();
                        storageId = storageDo.getId();
                    }
                }
            }
            if (storageId != 0) {
                OrderOutputProductAddReq productDetail = new OrderOutputProductAddReq();
                productDetail.setProductId(productId);
                productDetail.setCount(count);
                List<OrderOutputProductAddReq> productAddList = new ArrayList<>();
                productAddList.add(productDetail);
                OrderOutputPackageAddReq packageDetail = new OrderOutputPackageAddReq();
                List<OrderOutputPackageAddReq> packageAddReqList = new ArrayList<>();
                packageDetail.setProductList(productAddList);
                OrderOutputAddReq addReq = new OrderOutputAddReq();
                BeanUtils.copyProperties(res, addReq);
                packageAddReqList.add(packageDetail);
                if (storageId != 0) {
                    addReq.setStorageId(storageId);
                    addReq.setPackageList(packageAddReqList);
                    orderOutputAddReqList.add(addReq);
                }
            } else {
                //剩余SKU都没有库存
                failOrders.add(String.format("%s(%s库存不足)", orderAmazonDo.getAmazonOrderNumber(), productDo.getSellerSku()));
            }

        }

        if (orderOutputAddReqList.size() > 0) {
            operateRecordService.operateAddRecord(SysConstant.OPERATE_CLICK_SEND, orderAmazonDo.getId(), userId,4);
        }
        for (OrderOutputAddReq outputAddReq : orderOutputAddReqList) {
            StringBuilder sku = new StringBuilder();
            int cout = 0;
            for (OrderOutputProductAddReq orderOutputProductAddReq : outputAddReq.getPackageList().get(0).getProductList()) {
                cout = cout + orderOutputProductAddReq.getCount();
                if (StringUtils.isNotBlank(sku)) {
                    sku.append(",");
                }
                sku.append(productInfoDao.selectById(orderOutputProductAddReq.getProductId()).getCommoditySku());
            }
            outputAddReq.setSku(sku.toString());
            outputAddReq.setCount(cout);
        }
        Map map = new HashMap();
        map.put("orderList", orderOutputAddReqList);
        map.put("failedList", failOrders);
        map.put("storageList", storageDao.selectList(null));
        return SingleResult.success(map);
    }

    @Override
    public SingleResult sendOutMatch(List<OrderOutputAddReq> orderOutputAddReqList, Long userId) {
        List<String> failOrders = new ArrayList<>();
        failOrders.addAll(outputService.addAmazonList(orderOutputAddReqList, userId));
//        return SingleResult.success(String.format("成功导出%d个发货单", orderOutputAddReqList.size() - failOrders.size()), failOrders);;
        if (failOrders.size() > 0) {
            return SingleResult.failure("300", SysConstant.EXPORT_OUT_ORDER_SUCCESS_ID, failOrders, orderOutputAddReqList.size() - failOrders.size());
        } else {
            return SingleResult.success(failOrders);
        }
    }

    private void sufficientFundsCheck(Long companyId) {
        if (!companyAccountService.getIsDue(companyId)) {
            throw new NotSufficientFundsException(ErrorEnum.NOT_SUFFICIENT_FUNDS);
        }
    }

    private Long getProductId(String sellerSku, Long companyId) {
        QueryWrapper productWrapper = new QueryWrapper();
        productWrapper.eq("commodity_sku", sellerSku);
        productWrapper.eq("company_id", companyId);
        productWrapper.last("limit 1");
        ProductInfoDo productInfoDo = productInfoDao.selectOne(productWrapper);
        if (productInfoDo == null) {
            QueryWrapper skuWrapper = new QueryWrapper();
            skuWrapper.eq("sub_sku", sellerSku);
            skuWrapper.eq("company_id", companyId);
            skuWrapper.last("limit 1");
            ProductSkuMapDo productSkuMapDo = productSkuMapDao.selectOne(skuWrapper);
            if (productSkuMapDo == null) return null;
            return productSkuMapDo.getProductInfoId();
        } else {
            return productInfoDo.getId();
        }
    }

    private Long getSubProductId(String sellerSku, Long companyId) {
        QueryWrapper skuWrapper = new QueryWrapper();
        skuWrapper.eq("sub_sku", sellerSku);
        skuWrapper.eq("company_id", companyId);
        ProductSkuMapDo productSkuMapDo = productSkuMapDao.selectOne(skuWrapper);
        if (productSkuMapDo == null) return null;
        return productSkuMapDo.getProductInfoId();
    }


    @Override
    public AppletAmazonOrderDetailRes detail(Long id) {
        AppletAmazonOrderDetailRes res = new AppletAmazonOrderDetailRes();
        OrderAmazonDo amazonDo = dao.selectById(id);
        BeanUtils.copyProperties(amazonDo, res);
        LambdaQueryWrapper<OrderAmazonItemsDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderAmazonItemsDo::getOrderAmazonId, id);
        List<OrderAmazonItemsDo> itemsDoList = orderAmazonItemsDao.selectList(wrapper);
        List<AmazonOrderProductRes> productResList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(itemsDoList)) {
            for (OrderAmazonItemsDo itemsDo : itemsDoList) {
                AmazonOrderProductRes productRes = new AmazonOrderProductRes();
                BeanUtils.copyProperties(itemsDo, productRes);
                productResList.add(productRes);
            }
        }
//        res.setProductResList(productResList);
//
//        List<OperateRes> operateResList = new ArrayList<>();
//        LambdaQueryWrapper<OperateRecordDo> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(OperateRecordDo::getThirdId, id).eq(OperateRecordDo::getType, 4).orderByDesc(OperateRecordDo::getId);
//        List<OperateRecordDo> operateRecordDos = operateRecordDao.selectList(queryWrapper);
//        if (!CollectionUtils.isEmpty(operateRecordDos)) {
//            for (OperateRecordDo operateRecordDo : operateRecordDos) {
//                OperateRes operateRes = new OperateRes();
//                operateRes.setOperateTime(operateRecordDo.getOperateTime());
//                operateRes.setContent(operateRecordDo.getContent());
//                UserDo userDo = userDao.selectById(operateRecordDo.getOperateBy());
//                if (userDo != null) {
//                    operateRes.setOperateBy(userDo.getUserName() == null ? userDo.getUserAccount() :
//                            userDo.getUserName());
//                }
//                operateResList.add(operateRes);
//            }
//        }
//        res.setOperateResList(operateResList);

        return res;
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }


    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<OrderAmazonDo> wrapper = queryBuild(map);
        IPage<OrderAmazonDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<AppletAmazonOrderPageRes> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<AppletAmazonOrderPageRes> handlerListAfter(List<OrderAmazonDo> list) {
        List<AppletAmazonOrderPageRes> result = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (OrderAmazonDo amazonDo : list) {
                AppletAmazonOrderPageRes res = new AppletAmazonOrderPageRes();
                BeanUtils.copyProperties(amazonDo, res);
                result.add(res);
            }
        }
        return result;
    }

    private IPage<OrderAmazonDo> pageInit(Map<String, String> map) {
        IPage<OrderAmazonDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<OrderAmazonDo> queryBuild(Map<String, String> map) {
        QueryWrapper<OrderAmazonDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.and(i -> i.like("amazon_order_number", map.get("keyword").trim())
                    .or().like("ship_name", map.get("keyword").trim())
                    .or().like("commodity_sku", map.get("keyword").trim())
                    .or().like("ship_phone", map.get("keyword").trim()));
        }
        if (StringUtils.isNotBlank(map.get("startTime"))) {
            wrapper.gt("purchase_date", map.get("startTime"));
        }
        if (StringUtils.isNotBlank(map.get("endTime"))) {
            wrapper.lt("purchase_date", map.get("endTime"));
        }
        if (StringUtils.isNotBlank(map.get("orderStatus"))) {
            wrapper.eq("order_status", map.get("orderStatus"));
        }
        if (StringUtils.isNotBlank(map.get("fulfillmentChannel"))) {
            wrapper.eq("fulfillment_channel", map.get("fulfillmentChannel"));
        }
        if (StringUtils.isNotBlank(map.get("isSendOut"))) {
            wrapper.eq("is_send_out", map.get("isSendOut"));
        }
        if (StringUtils.isNotBlank(map.get("shopId"))) {
            wrapper.eq("shop_id", map.get("shopId"));
        }
        wrapper.eq("company_id", map.get("companyId")).orderByDesc("purchase_date");
        return wrapper;
    }

    @Override
    public SingleResult updateSysMemo(UpdateSysMemoReq req, Long userId, Long companyId) {
        OrderAmazonDo orderAmazonDo = this.baseMapper.selectById(req.getId());
        orderAmazonDo.setSystemMemo(req.getSystemMemo());
        this.baseMapper.updateById(orderAmazonDo);
        return SingleResult.success("编辑成功", null);
    }

    @Override
    public SingleResult systemMemoInit(Long id) {
        OrderAmazonDo orderAmazonDo = this.baseMapper.selectById(id);
        return SingleResult.success(orderAmazonDo.getSystemMemo());
    }

    private String getStr(String str) {
        if (str == null) {
            return "";
        }
        return str;
    }

}
